package com.yunfeisoft.controller.interceptor;

import com.applet.utils.AjaxUtils;
import com.applet.utils.SHA1Utils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * APP安全验证拦截器
 * Created by Jackie Liu on 2017/7/10.
 */
public class AppRequestInterceptor extends HandlerInterceptorAdapter {

    private static final String APP_SECRET = "weskndi980sdksndisonfnd9203083jdnkciedi2";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (true || isAccept(request)) {
            return true;
        }

        AjaxUtils.ajaxJsonWarnMessage("非法登录");
        return false;
    }

    /**
     * 验证请求URL的安全性，加密参数顺序为：client_type + app_token + _t + 私钥
     * @param request
     * @return
     */
    private boolean isAccept(HttpServletRequest request) {
        //请求的客户端类型：android、ios
        String client_type = request.getHeader("client_type");
        //请求的token，可以是user.id
        String app_token = request.getHeader("app_token");
        //请求时间戳
        String _t = request.getHeader("_t");
        //加密字符串，采用SHA1加密方式
        String _s = request.getHeader("_s");

        /*System.out.println("client_type:" + client_type);
        System.out.println("app_token:" + app_token);
        System.out.println("_t:" + _t);
        System.out.println("_s:" + _s);*/

        if (StringUtils.isBlank(client_type) || StringUtils.isBlank(app_token) ||
                StringUtils.isBlank(_t) || StringUtils.isBlank(_s)) {
            return false;
        }

        StringBuilder builder = new StringBuilder(client_type);
        builder.append(app_token).append(_t).append(APP_SECRET);
        String s_str = SHA1Utils.encode(builder.toString());
        if (s_str.equals(_s)) {
            return true;
        }

        return false;
    }
}
